﻿using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;
using System.IO;
using System.Net;
using System.Xml;

public partial class inbox : System.Web.UI.Page
{
    static DataTable dtreplies;
    static int userid;
    static int FlagDel = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt = SqlHelper.ExecuteDatatable(GlobalVariable.con, CommandType.Text, "select (FromNumber+' '+' '+Description) as DTF,FromNumber,Description from tbl_FromNumbers");
            ddlFromNumbers.DataSource = dt;
            ddlFromNumbers.DataTextField = "DTF";
            ddlFromNumbers.DataValueField = "FromNumber";
            ddlFromNumbers.DataBind();
            ddlFromNumbers.Items.Insert(0, "--Select Number--");
        }
    }
    protected void GridViewReplies_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridViewReplies.PageIndex = e.NewPageIndex;
        GridViewReplies.DataSource = dtreplies;
        GridViewReplies.DataBind();
    }
    protected void ChkAl_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chk = (CheckBox)GridViewReplies.HeaderRow.FindControl("ChkAll");
        if (chk.Checked == true)
        {
            foreach (GridViewRow row in GridViewReplies.Rows)
            {
                CheckBox chkItem = (CheckBox)row.FindControl("CheckBox1");
                chkItem.Checked = true;
            }
        }
    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        GridViewRow row = (GridViewRow)(sender as Control).Parent.Parent;
        int index = row.RowIndex;
        Label lblmsgid = GridViewReplies.Rows[index].FindControl("Label1") as Label;
        SqlHelper.ExecuteNonQuery(GlobalVariable.con, CommandType.Text, "delete from tbl_inbox where msgid='" + Convert.ToInt32(lblmsgid.Text) + "'");
        bindgrid();
    }
    protected void BtnDel_Click(object sender, EventArgs e)
    {

        for (int i = 0; i <= GridViewReplies.Rows.Count - 1; i++)
        {
            CheckBox chkboxselect = GridViewReplies.Rows[i].FindControl("chkSelect") as CheckBox;
            Label lblmsgid = GridViewReplies.Rows[i].FindControl("Label1") as Label;
            if (chkboxselect.Checked)
            {
                SqlHelper.ExecuteNonQuery(GlobalVariable.con, CommandType.Text, "delete from tbl_inbox where msgid='" + Convert.ToInt32(lblmsgid.Text) + "'");
                FlagDel = 1;

            }

        }
        if (FlagDel != 1)
        {
            Page.Controls.Add(new LiteralControl("<script language='javascript'> window.alert('Please select any one to delete.')</script>"));

        }
        if (FlagDel == 1)
        {
            Page.Controls.Add(new LiteralControl("<script language='javascript'> window.alert('Selected message deleted successfully.')</script>"));

        }
        bindgrid();
    }
    protected void GridViewReplies_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression == ViewState["MsgDate"].ToString())
        {
            if (ViewState["Sort_Order"].ToString() == "ASC")
                RebindData1(e.SortExpression, "DESC");
            else
                RebindData1(e.SortExpression, "ASC");
        }
        else
            RebindData1(e.SortExpression, "ASC");
    }
    private void RebindData1(string sColimnName, string sSortOrder)
    {
        DataTable dt = (DataTable)Cache["dt1"];
        dt.DefaultView.Sort = sColimnName + " " + sSortOrder;
        GridViewReplies.DataSource = dt;
        GridViewReplies.DataBind();
        ViewState["SentDateTime"] = sColimnName;
        ViewState["Sort_Order"] = sSortOrder;
    }
    protected void ddlFromNumbers_SelectedIndexChanged(object sender, EventArgs e)
    {
        bindgrid();
    }

    private void bindgrid()
    {
        dtreplies = SqlHelper.ExecuteDatatable(GlobalVariable.con, CommandType.Text, "select * from tbl_inbox where MsgTo='" + ddlFromNumbers.SelectedValue + "'");
        GridViewReplies.DataSource = dtreplies;
        GridViewReplies.DataBind();
        Cache["dt1"] = dtreplies;
        ViewState["MsgDate"] = "MsgDate";
        ViewState["Sort_Order"] = "ASC";
        GridViewReplies.Sort("MsgDate", SortDirection.Descending);
        if (GridViewReplies.Rows.Count > 0)
        {
            BtnDel.Visible = true;
            btnDownload.Visible = true;
            lblPPR.Visible = true;
            ddlShowRecords.Visible = true;
            btnOptOutSelected.Visible = true;
            txtSearch.Visible = true;
            Button2.Visible = true;
        }
        else
        {
            txtSearch.Visible = false;
            Button2.Visible = false;
            btnOptOutSelected.Visible = false;
            BtnDel.Visible = false;
            btnDownload.Visible = false;
            lblPPR.Visible = false;
            ddlShowRecords.Visible = false;
            //lblmsgStatus.Text = "";
        }
    }
    protected void btnDownload_Click(object sender, EventArgs e)
    {
        GridViewReplies.AllowPaging = false;
        GridViewReplies.Columns.RemoveAt(0);
        GridViewReplies.Columns.RemoveAt(0);
        GridViewReplies.Columns.RemoveAt(0);
        GridViewReplies.Columns.RemoveAt(3);
        GridViewReplies.Columns.RemoveAt(3);
        dtreplies = SqlHelper.ExecuteDatatable(GlobalVariable.con, CommandType.Text, "select * from tbl_inbox where MsgTo='" + ddlFromNumbers.SelectedValue + "'");
        GridViewReplies.DataSource = dtreplies;
        GridViewReplies.DataBind();
        DataFlow.Export("InboxData.xls", this.GridViewReplies);
    }
    protected void ddlShowRecords_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridViewReplies.PageSize = Convert.ToInt32(ddlShowRecords.SelectedValue);
        GridViewReplies.DataSource = dtreplies;
        GridViewReplies.DataBind();
    }
    protected void lbtnMsgFrom_Click(object sender, EventArgs e)
    {
        Session["MsgTo"] = null;
        Session["MsgFrom"] = null;
        GridViewRow row = (GridViewRow)(sender as Control).Parent.Parent;
        int index = row.RowIndex;
        Label MsgTo = (Label)GridViewReplies.Rows[index].FindControl("Label2");
        LinkButton MsgFrom = (LinkButton)GridViewReplies.Rows[index].FindControl("lbtnMsgFrom");
        Session["MsgTo"] = MsgTo.Text;
        Session["MsgFrom"] = MsgFrom.Text;
        Button1_ModalPopupExtender.Show();
    }
    protected void btnSendReply_Click(object sender, EventArgs e)
    {
        string MsgTo = Session["MsgTo"].ToString();
        string MsgFrom = Session["MsgFrom"].ToString();
        DateTime zonetime = getClientTime(DateTime.UtcNow.ToString(), "-06:00");
        DateTime ScheduleDateTime = Convert.ToDateTime(txtDate.Text + " " + DropDownListHour.SelectedValue + ":" + DropDownListMinute.SelectedValue + " " + ddlAMPM.SelectedValue);
        if (ScheduleDateTime > zonetime)
        {
            //SqlHelper.ExecuteNonQuery(GlobalVariable.con, CommandType.Text, "insert into tbl_SentMessages (MsgTo,MsgText,MsgStatus,UserId,groupid,SentDateTime,ScheduleDateTime,smsDeliveryTime,TimeZone,Frequency,TillDate) values('" + txtSingleNumber.Text.Trim() + "','" + message + "','" + GlobalVariable.MsgStatus.scheduled.ToString() + "','" + Convert.ToInt32(lbluid.Text) + "','" + ddlSubGroup.SelectedValue + "','" + DateTime.Now + "','" + ScheduleDateTime + "',null,'" + ddlTimeZone.SelectedValue + "','" + ddFrequency.SelectedValue + "','" + Convert.ToDateTime(txtTillDate.Text) + "')");
            SqlHelper.ExecuteNonQuery(GlobalVariable.con, CommandType.Text, "insert into tbl_SentMessages (MsgFrom,MsgTo,MsgText,MsgStatus,UserId,GroupId,SentDateTime,ScheduleDateTime,smsDeliveryTime,TimeZone) values('" +
                MsgTo + "','" + MsgFrom + "','" + txtReplyMessage.Text + "','" + GlobalVariable.MsgStatus.scheduled.ToString() + "','" + null + "','" + null + "','" + DateTime.Now + "','" + ScheduleDateTime + "',null,'-06:00')");
            lblmsg.Text = "Message scheduled. Send another or click on close button above to close the panel.";
        }
        else
        {
            lblmsg.Text = "Please select future time";
            //Page.Controls.Add(new LiteralControl("<script language='javascript'> window.alert('" + SelectGroup + "')</script>"));
        } 
    }
    public static DateTime getClientTime(string date, object O)
    {
        if (O != null)
        {
            string Temp = O.ToString().Trim();
            if (!Temp.Contains("+") && !Temp.Contains("-"))
            {
                Temp = Temp.Insert(0, "+");
            }

            ReadOnlyCollection<TimeZoneInfo> timeZones = TimeZoneInfo.GetSystemTimeZones();
            DateTime startTime = DateTime.Parse(date);
            DateTime _now = DateTime.Parse(date);
            foreach (TimeZoneInfo timeZoneInfo in timeZones)
            {
                if (timeZoneInfo.ToString().Contains(Temp))
                {
                    //Response.Write(timeZoneInfo.ToString());
                    //string _timeZoneId = "Pacific Standard Time";
                    TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById(timeZoneInfo.Id);
                    _now = TimeZoneInfo.ConvertTime(startTime, TimeZoneInfo.Utc, tst);

                    break;
                }
            }
            return _now;
        }
        else
            return DateTime.Parse(date);
    }
    protected void btnOptOutSelected_Click(object sender, EventArgs e)
    {
        int countopt = 0;
        int noop = 0;
        int totaln = 0;
        string numbers = "";
        for (int i = 0; i <= GridViewReplies.Rows.Count - 1; i++)
        {
            CheckBox chkboxselect = GridViewReplies.Rows[i].FindControl("chkSelect") as CheckBox;
            LinkButton lblMsgTo = GridViewReplies.Rows[i].FindControl("lbtnMsgFrom") as LinkButton;
            Label lblmsgid = GridViewReplies.Rows[i].FindControl("Label1") as Label;
            if (chkboxselect.Checked)
            {
                totaln++;
                object nmbr = SqlHelper.ExecuteScalar(GlobalVariable.con, CommandType.Text, "Select ContactId from tbl_groupcontacts where MobileNumber='" + lblMsgTo.Text + "'");
                if (nmbr != null)
                {
                    SqlHelper.ExecuteNonQuery(GlobalVariable.con, CommandType.Text, "update tbl_groupcontacts set Unsubscribed='true' where MobileNumber = '" + lblMsgTo.Text + "'");
                    countopt++;
                }
                else
                {
                    noop++;
                    object opt = SqlHelper.ExecuteScalar(GlobalVariable.con,CommandType.Text,"select GroupId from tbl_group where GroupName='Opt Outs'");
                    if (opt != null)
                    {
                        int abc = Convert.ToInt32(opt.ToString());
                        SqlHelper.ExecuteNonQuery(GlobalVariable.con, CommandType.Text, "insert into tbl_groupcontacts (groupid,MobileNumber,EmailId,FirstName,LastName,CurrentDT,Unsubscribed) values(" + abc + ",'" + lblMsgTo.Text + "','" + null + "','" + null + "','" + null + "','" + DateTime.Now + "','true')");
                    }
                }
                SqlHelper.ExecuteNonQuery(GlobalVariable.con, CommandType.Text, "delete from tbl_inbox where msgid='" + Convert.ToInt32(lblmsgid.Text) + "'");
            }
        }
        bindgrid();
        string SelectGroup = "";
        SelectGroup = "" + totaln + " contacts opted out from database.";
        Page.Controls.Add(new LiteralControl("<script language='javascript'> window.alert('" + SelectGroup + "')</script>"));
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        if (txtSearch.Text == string.Empty)
        {
            string SelectGroup = "Enter valid information to search.";
            Page.Controls.Add(new LiteralControl("<script language='javascript'> window.alert('" + SelectGroup + "')</script>"));
        }
        else
        {
            SearchData();
        }
    }
    private void SearchData()
    {
        Int64 a = 0;
        string ColName;
        string ColName2 = "";
        DataSet ds1 = new DataSet();
        try
        {
            a = Convert.ToInt64(txtSearch.Text);
            ColName = "MsgFrom";
            ds1 = SqlHelper.ExecuteDataset(GlobalVariable.con, CommandType.Text, "select * from tbl_inbox where " + ColName + " like '" + txtSearch.Text + "%' and MsgTo='" + ddlFromNumbers.SelectedValue + "'");
        }
        catch
        {
            //ColName = "FirstName";
            //ColName2 = "LastName";
            //ds1 = SqlHelper.ExecuteDataset(GlobalVariable.con, CommandType.Text, "select * from tbl_inbox where MsgText like'" + txtSearch.Text + "%' and MsgTo='" + ddlFromNumbers.SelectedValue + "'");
            //string SelectGroup = "Sorry no info available in inbox.";
            //Page.Controls.Add(new LiteralControl("<script language='javascript'> window.alert('" + SelectGroup + "')</script>"));
        }
        DataTable dt1 = ds1.Tables[0];
        if (dt1.Rows.Count > 0)
        {
            GridViewReplies.DataSource = dt1;
            GridViewReplies.DataBind();
            Cache["dt1"] = dt1;
            ViewState["MsgDate"] = "MsgDate";
            ViewState["Sort_Order"] = "ASC";
            GridViewReplies.Sort("MsgDate", SortDirection.Descending);
            if (GridViewReplies.Rows.Count > 0)
            {
                BtnDel.Visible = true;
                btnDownload.Visible = true;
                lblPPR.Visible = true;
                ddlShowRecords.Visible = true;
                btnOptOutSelected.Visible = true;
            }
            else
            {
                btnOptOutSelected.Visible = false;
                BtnDel.Visible = false;
                btnDownload.Visible = false;
                lblPPR.Visible = false;
                ddlShowRecords.Visible = false;
                //lblmsgStatus.Text = "";
            }
        }
        else
        {
            string SelectGroup = "Sorry no info available in inbox.";
            Page.Controls.Add(new LiteralControl("<script language='javascript'> window.alert('" + SelectGroup + "')</script>"));
        }
    }
    private void MessageBox(string strMsg)
    {
        Label lbl = new Label();
        lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert(" + "'" + strMsg + "'" + ")</script>";
        Page.Controls.Add(lbl);
    }
}
